import express from 'express';
import { AuditLogController } from '../controllers/auditLogController';
import { auth } from '../middleware/auth';
import { validateAuditLog } from '../middleware/validators/auditLogValidator';
import { createRouteHandler } from '../middleware/routeHandler';
import { AuditLogQuery, AuditLogResponse, AuditLogStats } from '../types/audit';
import { AuditLogDocument } from '../models/auditLog';

const router = express.Router();

// Apply base middleware
router.use(auth);

// === Route Configurations ===
const routes = {
  // Get audit logs list
  getAll: createRouteHandler({
    handler: AuditLogController.getAll,
    validator: [validateAuditLog('query')]
  }),

  // Get audit log stats
  getStats: createRouteHandler({
    handler: AuditLogController.getStats,
    roles: ['admin'],
    validator: []
  }),

  // Get single audit log
  getOne: createRouteHandler({
    handler: AuditLogController.getOne,
    validator: [validateAuditLog('getOne')]
  }),

  // Create new audit log entry
  create: createRouteHandler({
    handler: AuditLogController.create,
    roles: ['admin'],
    validator: [validateAuditLog('create')]
  }),

  // Cleanup old audit logs
  cleanup: createRouteHandler({
    handler: AuditLogController.cleanupLogs,
    roles: ['admin'],
    validator: [validateAuditLog('cleanup')]
  })
};

// === Route Definitions ===

// Get audit logs list with filtering and pagination
router.get('/', routes.getAll);

// Get audit log statistics
router.get('/stats', routes.getStats);

// Get single audit log by ID
router.get('/:id', routes.getOne);

// Create new audit log
router.post('/', routes.create);

// Clean up old audit logs
router.post('/cleanup', routes.cleanup);

// === Type Assertions ===
// These type assertions help ensure our route configurations match
// the expected types from the controller
type GetAllConfig = {
  params: {},
  response: AuditLogResponse,
  query: AuditLogQuery
};

type GetStatsConfig = {
  params: {},
  response: AuditLogStats
};

type GetOneConfig = {
  params: { id: string },
  response: AuditLogDocument
};

type CreateConfig = {
  params: {},
  body: Partial<AuditLogDocument>
};

type CleanupConfig = {
  params: {},
  body: {
    days?: number;
    types?: string[];
  }
};

// Verify route types match controller types
const _typeChecks = {
  getAll: routes.getAll as unknown as GetAllConfig,
  getStats: routes.getStats as unknown as GetStatsConfig,
  getOne: routes.getOne as unknown as GetOneConfig,
  create: routes.create as unknown as CreateConfig,
  cleanup: routes.cleanup as unknown as CleanupConfig
};

export default router;
